                                 TimPlayer
                                 =========


  1     Introduction to Trackers
  1.a     Channels, rows, frames
  1.b     Patterns and sequences
  1.c     Global variables
  1.d     Replay
  1.e     Playing notes in a channel
  1.f     Instruments and samples
  1.f.1     A Digital Sample
  1.f.2     Replaying the sample (Mixing)
  1.f.3     Instrument or sample?
  1.f.4     Samples
  1.f.5     Instruments
  1.f.6     Special Cases
  1.g     Note control
  2     Internal storage
  3     Controllers and Effects
  3.a     Generic controller info and effects
  3.b     Global controllers
  3.b.1     Song Flow controller
  3.b.2     Song Tempo controller
  3.b.3     Song Frames controller
  3.b.4     Global Volume controller
  3.c     Channel controllers
  3.c.1     Channel Volume controller
  3.d     Notes: sample, pitch, filter, volume and panning
  3.d.1     Instrument/Sample controller
  3.d.2     Pitch/Filter controller
  3.d.3     Note Volume controller
  3.d.4     Panning controller
  4       Logging
  5       Limitations
  6       Volume ramping


1 Introduction to Trackers
--------------------------

1.a) Channels, rows, frames

The general principle of a tracker is to control sound producted in <C>
independant channels by providing to each channel a sequence of instructions
to form a soundtrack.

Derived from the way a score notation work, we should at least be able to
specify a sequence of notes played with a given instrument at a given tempo.
The most obvious presentation is of course a table with <2*C> columns for
<C> channels and where each row list the note and instrument to be played
(if any) at a givem beat for a given column. Each beat has a duration
defined by a global Tempo value <T>.

This is of course not enough, on a real instrument you can play notes in
various ways: quieter, louder, for some you can bend the pitch to into
another notes, etc. In other words, you need to be able to apply effects.
So of course your table now includes an additional column allowing you
to specify an effect and a parameter (like set volume to x or slide the
pitch by y), so your table can for example take the form of:

Beat Nr     Channel 1     Channel 2    Channel 3    Channel 4
  00        C#1 16 202    --- -- ---   F-2 04 A04   --- -- ---
  01        --- -- 202    --- -- ---   --- -- A04   --- -- ---
  02        --- -- 202    --- -- ---   --- -- A04   --- -- ---
                               Note <- /   |   \-> Effect (A) and param (04)
                                           V
                                       Instrument Nr

Remark: the note is exprimed here in a standard representation of a semitone
        and an octave number. An octave is divided in 12 semitones
        named (from low to high pitch): C C# D D# E F G G# A A# B.

Having only one effect column was rapidly found insuffisant when you can
have control on the pitch, the volume, stereo positionning so some programs
often provide additionnal columns in the form of a volume column or a second
effects column.

As you can notice in the little example, you can see than the same effects
and values are repeated in the 3 rows. Taking the ProTracker effect naming
convention, this would slide the pitch of the note in channel 1 down by 2
every beat and the volume of the note in channel 3 by 4. Finding this
tedious, someone invented the notion of a global speed parameter of value <S>.

Now one row in the table has not a duration of 1 beat but of <S> frames (ticks).
The note and one-shot effects are played at the start of the first frame
while the other effects (like sliding) are repeated the other <S> - 1 frame.





1.b) Patterns and sequences

Having to fill in one big table is not so easy, you'd like to decompose
your table in smaller independent chunks, be allow to write several variants
of a chunk and easily swap those variant within your soundtrack, use the
same chunks at different places in your soundtrack, etc. Well, this is
exactly what trackers do, these chunks are called patterns and
the soundtrack is composed of a sequence of <N> pattern numbers. So if your
sequence is 01 02 04 02 04, the tracker will play pattern 01 then patterns
02 and 04, then once again patterns 02 and 04, while pattern 03 was left
unused (containing probably a rejected variant of pattern 02 or 04).

The earlier trackers used patterns of a fixed number of rows, while later
ones usually allow you to fix the number of rows in each pattern.

Digital Symphony uses another variant on the theme of patterns. The patterns
contain only 1 channel but the sequence now specifies <C> patterns for each
of the <N> positions in the sequence. These kind of files can be easely
transformed in the traditionnal form by defining one multi-channel
pattern for each position in the sequence and combining in it each of
the 1-channel patterns specified for that sequence position.





1.c) Global variables

From section 1.a) you are already aware that the replay can be affected
by some global variables like Tempo <T> and Speed <S>.

The Tempo <T> defines the the number of frames per seconds
as <T> / <B> where <B> is the tempo base (2.5 for most trackers like MOD).
The Speed <S> defines the duration of a pattern row as <S> frames.

The tempo may also be defined by the 2 variables <BPM> (beats per minutes)
and <FPB> (frames per beats). The number of frames per seconds
then becomes <BPM> * <FPB> / 60, i.e. <T> = <BPM> * <FPB> * <B> / 60.
If we use the lines per beat, <FPB> = <LPB> * <S>,
tempo takes the form <T> = <BPM> * <LPB> * <S> * <B> / 60.

These are the most usual forms but some other forms exists which must be
carefully translated into the supported definitions:
- the Farandole tempo defines the duration of a row as x times a base duration.
  It look like speed <S> except that when you look at slide effects the amount
  is given for the whole row as if <S> = 1.
- X-Tracker uses rows per beat <RPB> instead of <FPB>. Slides values are once
  again for the whole row and effects specifying delays or intervals use
  fractions of a row. The documentation and code derives a speed
  from the tempo, but it is just to keep the interrupt driven controller
  updates into a given frequency range and to smooth out the slides;
  meaning its some internal work mecanism, not a frame definition
  in the tracker sense.
- ...

The Global Volume <V> controls the global volume level of the sound track
and is used to fade-out the end of the soundtrack.

So we have actually 6 global variables associated to a soundtrack.
- Tempo base <B>
- Tempo <T>
- Beats per minutes <BPM>
- Frames per beat <FPB>
- Speed <S>
- Global Volume <V>.

Defaults values are often provided in the file header but they can usually
be modified during playback by effects defined in the patterns.





1.d) Replay

Basically, replaying the file consists of looping on each row of the pattern
specified in each pattern row.

Of course this was to simple so trackers introduced effects like:
- jump: jump to start of sequence pos x.
- break: jump to row x (in next seq. position or the one specified by a jump).
- line: jump to row x (in current seq. position or the one specified by a jump).
- delay: row duration is extend by x frames.
- repeat: multiply row duration by row x times.

And other features like
- a restart position on the sequence to move back when reaching
  the end of the sequence.
- special markers in sequence for skipping a sequence position or marking
  the end of the sequence (i.e. splitting the song in sub-songs).


This means that after playing a frame some calculations must be done
so player to determine what to play next. Here is the pseudo-code for it:

sequence position = 0
row = 0
frame = 0 // [0, row_speed[
row_frame = 0 // [0, row_speed * (1 + repeats)]

goto read_pattern

loop
{

play_frame:
	for each channel
	{
		if (note delay = frame)
		    new_note = 1
		else if ((note delay = 0) and frame (row_frame for IT) = 0)
		    new_note = 1
		else
		    new_note

		if (new_note)
			start playing a new note if one is specified

		if (frame = 0)
		{
			apply one-shot effect if one is specified
		}
		else
		{
			apply repeating effect if one is specified
		}

		channel += 1
	}

	// maintain sound for duration of a frame
	...

new_frame:
	frame += 1
	row_frame += 1

	if (frame < row_speed)
		goto play_frame;

new_repeat:
	if (repeats > 0)
	{
		repeats -= 1
		frame = 0
		goto play_frame;
	}

new_row/pattern:
	loop_chn = -1
	// first treats loops within a pattern
	for each loop effect in row channels
	{
		if (effect value = 0)
		{
			// marks the start point of a loop
			if (loop_start[channel] <> row)
			{
				loop_start[channel] = row
				loop_end[channel] = -1
			}
		}
		else
		{
			// loop is in effect?
            if (loop_count[channel])
            {
				// yes
            	loop_count[channel] -= 1

				// continue to loop
            	if (loop_count[channel])
            	{
            		// we move to start of loop once more
					loop_chn = channel
				}
				else
				{
					// Some tracker avoid infinite loops
					// (i.e a single loop start followed by two loops ends)
					if (S3M/IT)
						loop_start[channel] = row + 1
					else
						loop_end[channel] = row // infi
				}
			}
			else
			{
				// no
				if (row > loop_start[channel])
				{
					loop_count[channel] = effect value
					loop_chn = channel
				}	
			}
		}
	}

	new_pattern = false

	// By default move to next row
	row += 1

	// a loop is active? with multiple active loops on same row
	// loop_chn is the highest channel which such a loop
	if (loop_chn >= 0)
	{
		row = loop_start[loop_chn]
		sequence position = current position
		if (loop_end[loop_chn] in (-1, current row)
		{
			// simple jump in pattern
			goto read_row
		}
		else
		{
			// second loop with same loop start, infinite loop
			// treat as pattern jump so that song duration ends here
			goto read_pattern
		}
	}

	for last position jump effect in row
	{
		// move to the specified sequence position
		// the first row of that pattern
		sequence position = value
		row = 0
		new_pattern = true
	}

	for last line/break effect in row
	{
		// move to specified row
		row = value;
		if (effect is break)
		{
			// in pattern of next sequence position
			// or pattern of jump sequence position
			row = value;
			if (new_pattern = false)
				sequence position += 1
			new_pattern = true
		}
	}

	if (new_pattern = false)
		goto read_row

read_pattern:
	// check validity of new sequence position
	loop
	{
		if (sequence position >= sequence length)
			sequence position = restart position

		pattern = pattern[sequence position]

		if (pattern is valid)
			exit loop

		if (pattern is end marker)
			sequence position = restart position
		else // Invalid, try next pos
			sequence position += 1
	}

	// reset loops (S3M)
		if (reset loop on pattern change)
		for each channel
		{
			loop_start[channel] = 0 // where to jump
			loop_count[channel] = 0 // counter, jump if > 0
			loop_end[channel] = -1  // last completed loop (infi. detection)
		}
	}

read_row:
	// check validity of new row
	if (row >= number or rows in pattern)
	{
		// move to the start of pattern in the next sequence position
		row = 0
		sequence position += 1
		goto new_pattern
	}

	// check tempo effects
	for each tempo effects in row
	{
		...
	}
	frame_duration = durations[tempo]

	// check seed effects
	row_speed = 0
	repeats = 0
	for each speed effects in row
	{
		if (effect is set) speed = value
		...
		if (effect is repeat) repeats = value
		if (effect is delay) row_speed += value
	}
	row_speed += speed

	// we are ready to play first frame of row
	row_frame = 0
	frame = 0
}





1.e) Playing notes in a channel

I'm going to describe in more details the working of the columns in a pattern
by using as an example a sequence of row (with ProTrack conventions):

    F#1 01 ---  -> Plays note F#1 with instrument 01
    --- -- ---  -> Continue playing note
    A-2 -- ---  -> Plays note A-2 using same instrument as before (01).
    --- -- 105  -> Continue playing note but slide pitch up by 05 per frame.
    C-3 03 A20  -> Plays note C-3, instr. 03 with volume of 20 (hexadecimal).

There is however a special case with effect "Portamento":

     D-1 01 ---  -> Play note D-1 with instrument 01
     C-3 -- 314  -> Portamento with value 14 to target C-3
     --- -- 314  -> Portamento with value 14 to previously define target

In the example, D-1 is used to play a new note, but C-3 in the second line
is used by the portamento to tell us that we are going to slide the pitch
by 14 increments per frame from D-1 to C-3. The third line mearly continues
to slide the pitch by 14 in direction of the previously define target (C-3).

That's for the basis. Now comes the comes the questions of combinations
left untold in every tracker documentation and handled in different ways
by various trackers:

1) what if I specify an instrument but no new note like here?

     --- 02 ---

In most trackers you just continue to play the existing note with its original
instrument but since it may be use by a later row which specifies a note but
no instrument, the tracker memorizes the instrument and resets playing
parameters to the default instrument settings (like a default volume). So:

     A-2 01 A10 -> Plays note A-2 with instr 01 with volume 10
     A-2 01 --- -> Plays note A-2 with instr 01 with default instr 01 volume
     --- 02 --- -> Continue previous note with default instr 02 volume
     A-2 -- A20 -> Plays note A-2 with instr 02 at volume 20

The list of playing parameters (see later) varies from tracker to tracker but
if an instruments defines default values for volume, volume swing, panning
and panning swing those are usually copied over during the reset of the playing
parameters. Playing switches like fade-out, sustain, envelopes are often reset
as well as positions withing envelopes and vibrato.

2) what happens when a portamento is applied while no note is playing?

In most trackers, nothing.

3) what happens when no instrument is defined for the very first note played?

In most trackers, nothing is played. (I think!).

4) what happens when the instrument specified does not exists?

Nothing new is played, the previous note is usually terminated.


!!! Attention !!! Here are some important variants:

ImpluseTracker:
- when only a new instrument is defined plays a new note with the new instrument
  unless it is the same as the previous one in which case it just resets
  the note volume to the instrument default.
  Exception: if the note maps to sample 0 for this instrument, the playing note
  is left unchanged.
- plays a new note when no note is currently playing when a note or sample with
  a portamento is defined.
- note cut in note column resets the last note number in which case nothing is
  played in the above cases if only an instrument without note is specified.

FastTracker2:
- an instrument without a note resets note with parameter of playing instrument
  instead of new one.

ScreamTracker3:
- an instrument (with or without a note) does affect the playing note only
  if the sample is defined.


1.f) Instruments and Samples

In the previous sections I mentionned several times playing a note x with
instrument y without defining exactly what an instrument is. The basis
of an instrument is a digitally sampled sound or "sample" for short.



1.f.1) A Digital Sample 

Sampling consists of recording a sound by mesuring its amplitude at
a fixed frequency Fs and converting those measures in a number.
Let say the Fs = 1000Hz, this means mesuring its amplitude every 0,001 seconds
(known as sampling period Ts = 1/Fs). The measures taken may be converted
to a number in different ways. This formatting usually is:

  * linear on x bits:

    Using x bits allows you to define values from 0 to 2^x - 1.
    Now let say that you represent your maximal amplitude (Amax) as 2^x - 1,
    you will be able to encode a A in the range 0 to Amax as the integer
    part of (2^x - 1) * A/Amax. This means of course that your digital
    representation will differ from the real signal with a maximal
    error of up to Amax / (2^x - 1) within the range [0, Amax] and
    with an error (A - Amax) when values above Amax are "saturated" to Amax.

    This means of course the more bits you use the more accurate your digital
    representation becomes but is limited by the capacity of your microphone
    to accuratly measure the sound and of the human ears in distinguishing
    small amplitude differences.

    Signed or unsigned encoding?

    Sound as most signals can of course have negatives values you have several
    ways to encode this:
    
    - the ususal computer signed representation were range [0, 2^(x-1) - 1]
      is used to store positive values and negatives are stored as
      [2^x + 1 + val]. Lest say we use 8 bits to encode values in range
      [-128, 127], the means that the binary 1xxxxxxx represents a negative
      value, value 10000000 representing -128, 11111111 representing -1.
      0xxxxxxx represents a positive value: 00000000 is zero and 0111111 is 127.

    - the unsigned representation. Values are encoded an unsigned in range
      [0, 2^x - 1] representing the difference to the most negative value.
      Let say that that we use once again to encode values un range [-128, 127],
      this means that 0xxxxxxx represents a negative value, 00000000
      representing -128, 01111111 representing -1. 1xxxxxxx represents
      a positive value with 10000000 representing 0 and 11111111 representing
      127.
      
    I never understoud why the unsigned representation exists as it must
    be converted to a signed representation before it can be manipulated.
    The conversion between the two representations is made by toggling
    the top bit of the value, 1 becoming 0 and 0 becoming 1. Computer wise
    this means performing an exclusive-OR with a constant were the top
    bit is set to 1 and the other bits to 0.
    
    We will always convert the unsigned representation to a signed one after
    loading.
    
    Decompression
    
    Some trackers use compressed forms like LZW to reduce the size of the sample
    in the file. The loaders will have to decompress them in memory.

  * non-linear values on x bits:

    Human ears are far less sensible to in a given variation of amplitude
    at high volume than at low volume. This is why you will find several
    encoding schemes to compress the high amplitude range like A-law
    or µ-law compressing 12-bits as an 8-bit representation. These
    representations must be expended to signed value using conversion
    tables to signed linear values before they can be manipulated.

Note:
Digital theory will tell the digital sampling at frequency Fs performs
a transformation of the input signal in the frequency domain, leaving
frequencies in range [-Fs/2, Fs/2] more or less intact but translate
(with some attenuation) the frequences in range [n*F - F/2, n*F + F/2]
into the range [-F/2, F/2]. This means that means that ideally your input
should be filtered first to leave out any frequencies above Fs/2.



1.f.2) Replaying the sample (Mixing)

So we have the sound of our instrument sampled at a given frequency Fs.
Let's assume that we play it as is, the problem is that the sound card
on the machine will work at a different frequency Fmix outputting one value
fot times T(n) = n * 1/Fmix while the sample has values S(n') for times
T(n') = n' * 1/ Fs. This means that to make the transformation
n'' = n * Fs/Fmix, however we have a problem n' is an integer while the
multiplication of the integer n by Fs/Fmix will result in a non integer
value n'', meaning that we dont have a value for that precise time and that
we need to approximate it. There are several ways to do it:

- truncate n'' to an integer n' = Integer(n'') and use the sample S(n').
- truncate n'' to an integer n' = Integer(n'') and interpolate a value
  from sample S(n') and adjacent values. The most simple is of course
  a linear interpolation which reconstruct the signal between successive
  values as line segments between the two values. This can be generalised
  as a polymon or order x passing by x + 1 successive values.
- read the part of digital signal processing concerning sampling frequency
  conversion which explains the most accurate way to convert a signal
  sampled at Fs into a signal sampled at Fmix. All that I remember is
  it involves the use of large computation intensive FIR filters and
  the need to pre-filter the original signal if Fs > Fmix.


Now of course our instrument will be played at various pitches according
to the selected note. By the definition of a noted played an octave higher
has a pitch twice higher. So if C-1 is the base note played at Fs/Fmix,
C-2 is played at 2 * Fs/Fmix, C-3 at 2*2 * Fs/Fmix, etc. In semitones
this means that note x is played at:

   Fs' = 2^(x/12) * Fs/Fmix

where x is the (signed) number of semitones between the note and the base note.



1.f.3) Instrument or sample?

In early trackers, the instrument number refered to a little structure
pointing to a sample and a few attributes such as length of the sample,
type of sample, loop starting and points. More recently with extented
ranges of 10 octaves it was deemed to using a single sample to replay
an instrument may not be a good idea:

- First, the real instrument may be non-linear and sound somewhat differently
  at a different pitch.
- Second, the note at the end of section 1.f.1 applies to the replay
  of notes. Even if a sample was filtered correctly in range [0, Fs/2],
  replay the sample at a give note number will stretch the signal in
  frequency demain to [0, Fs'/2] where Fs' is the frequency calculated
  above. This means that with a high enough pitch Fs' > Fmix and the signal
  contain some high frequencies F which will be translated into an unwanted
  low frequency signal at F - Fmix.

So later tracker redefined the old intrument definition as a sample
and defined the instrument as a mapping translating each possible note
of an instrument, as a sample number and a sample note. I will explain it
with an exemple. Let say that we have 3 octaves and that I sample a note
of an real instrument at Fs for use as base note C-1, then that I sample
the instrument twice more at Fs but with the note played respectively
1 and 2 octaves higher. If I play sample 2(3) at note C-1 it will sound as
if I played sample 1 at C-2(3). So to define an instrument using sample 1
for octave 1, sample 2 for octave 2 and sample 3 for octave 3, the note mapping
becomes:

   Instr. Note    Sample   Nr.  Note
          C-1       ->       1  C-1
          ...
          B-1       ->       1  B-1
          C-2       ->       2  C-1
          ...
          B-2       ->       2  B-1
          C-3       ->       3  C-1
          ...
          B-3       ->       3  B-1

So this means that trackers behave in two different ways which are called
sample mode and instrument mode.



1.f.4) Samples

A sample is defined by the following parameters:

- the sample length in number of data samples.
- the sample format (number of bits, signed/insigned, ...).
- the sample frequency when playing the central note.
  Note: most formats defining a frequency use samples at 8363 Hz internally
        but add a relative tone (see below) corresponding to the 8363 Hz
        to sample frequency shift when a new note is played.
        You might think it is the same, i.e. a C-5 for a sample at 2*8363 Hz
        is the same as playing a C-6 for a sample at 8363 Hz but there are
        some differences:
        + for Amiga mode pitch period is divided by 2 one octave higher
          and so slides and vibrato are basically twice as deep around C-6
          than around C-5.
        + what happens when you apply the relative tone to a new note
          and the result is outside the allowed pitch limits?
- the sample data.
- a default volume which will be used when the note starts playing
  unless a volume effect overwrides it.
- a scale volume which will be used to rescale the sample volume
  independently from the note volume.
- an optionnal default panning (stereo position) to be used when the note
  starts playing.
- a relative tone, a given number of 1/256 semitones added when a note
  is played.
  This covers MOD sample finetune (x/8 haftones), XM reltones (x semitones)
  and for most others formats translation of sample frequency to 8363 Hz.
- an optionnal name.
- an optionnal filename.

- an optionnal vibrato with:
  - speed, depth, type (see vibrato effect).
  - rate at which the vibrato expends from 0 to the specified depth
    after each frame.

- an optionnal "sustain" loop with:
  - a start point (offset to first data sample in the loop).
  - an end point (offset to last data sample in the loop).
  - looping style:
       normal (start to end, start to end, start to end, ...).
       bidirectionnal (start to end, end to start, start to end, ...).

- an optionnal loop with:
  - a start point (offset to first data sample in the loop).
  - an end point (offset to last data sample in the loop).
  - looping style:
       normal (start to end, start to end, start to end, ...).
       bidirectionnal (start to end, end to start, start to end, ...).

When a loop is defined the sample is not played from the start of the sample
to the end of the sample and then stopped, but played first from the start
of the sample to the end loop point, then repeatedly between the loop limits
till the note is stopped, either explicitely by an effect or implicitely
when a new note is played.

When the note starts, the player will try in the following order of preference
to:
- use the sustain loop if one is defined,
- use the normal loop if one is defined,
- use no loop.

If while playing the note is released, the note will revert to normal loop
if one is defined, or no loop at all.



1.f.5) Instruments

An instrument is defined by the following parameters:

- a name.
- a filename.
- a note map translating instrument notes into sample number and notes.
- an optionnal volume envelope.
- an optionnal panning envelope.
- an optionnal pitch envelope.
- an optionnal filter envelope.
- a fadeout volume (see next section).
- a default volume.
- an optionnal default panning.
- a volume swing in % by which to randomize the note volume when the note
  is started.
- a pannning swing by which to randomize the note panning when the note
  is started.
- a pitch/panning center and seperation, altering the note panning
  in function of the note number when the note is started.
- a filter cutoff and resonance parameters.
- a new note action (see next section).
- a duplicate check type and duplicate note action (see next section).

An envelope is a list of (frame number, values) couples forming a curve
by which to automatically alter a note's parameter. Envelope parameters
are:

- nr of (frame nr, value) couples.
- list of (frame nr, value) couples.
- an optionnal sustain loop with:
  - a start point nr.
  - an loop end point nr.
- an optionnal loop with:
  - a start point nr.
  - an loop end point nr.
- a carry flag: if you play the same note as before with this flags set,
  then envelope will not be reset.

Envelope affects the note in the following way:
- volume envelope rescales the note volume, when the end of the envelope
  is reached, a note fade occurs (see next section).
- panning envelope moves the panning relatively to the note's panning.
- pitch envelope alters the pitch relatively to the note's pitch.
- the filter envelope rescales the filter cutoff.



1.f.6) Special cases

In the song header pSampleDef and pSampleNoMap points to 2 pseudo samples
which are used to define the behaviour when the sample nr specified
in the pattern is greater than the number of samples in the file
and when an instrument does not map to a sample (see below).
The default behaviour, which can be modified by the format loaders,
is in the first case to treat it as a sample of size 0 and volume 0
and in the later case to behave as if no instrument nor note was specified.






1.g) Note control

The previous section may have already provided some hints just playing
a sample is note enough to correctly render. Some instruments will play
continue to play a note while the key corresponding to the note is pressed,
then the sound will slowly fadeout after you release the key. Also on
a piano each note as its own chord, so if you press the same key as before
the previous note will be replaced by the new one but the other notes
will not be affected.

So first is a series of actions to "end" a note:

* Note cut:
  - the note is stopped.

* Note fade:
  - start fading the note volume each frame by instrument fadeout parameter
    or cut note if fadeout is 0.

* Note off (IT):
  - sample and envelopes "sustain" loops are turned off.
  - if the volume envelope does not exists or uses a normal loop
    fade note.

* Note off XM:
  - sample and envelopes "sustain" loops are turned off.
  - if the volume envelope exists fade note, else set note volume to 0.

* Note sustain off:
  - sample and envelopes "sustain" loops are turned off.

* Note continue:
  - let the note play as before.
  
Now we have to introduce an ImpulseTracker concept, virtual channels! Like
with a real instrument, playing a "new" note doesn't always stop the "current"
note, it becomes a "past" note which continues to be played unaffected
in general by the effects which are applied to the new "current" note
in the channel. These past note are kinda played on a "virtual channel".

So as seen in the previous section instruments now have the following
attributes:
- new note action, action to be performed on a current note using this
  uses this instrument when a new note is played on a channel.
- duplicate note action, action to be performed on past notes when
  a new note using this instrument is applied. The action is only applied
  on past notes verifying the duplicate check type:
   - off, do not affect past notes.
   - note, affect only past notes using the same note number.
   - sample, affect only past notes using the same sample number.
   - instrument, affect only past notes using the same instrument number.
   - all, affect all past notes.





2) Internal storage

Patterns consume much space while mostly empty, so they are stored in compressed
form within TimPlayer:

Here is a procedure to decode a pattern:

foreach row in pattern
{
  read row length (2 bytes)

  if (row length > 0)
  {
    // global effects (grouped by controller)
    repeat
    {
      read controller info (1 byte)
      if (controller info = 0)
        exit repeat

      nr of effects = the 4 high bits of controller info
      ctrl id = the 4 low bits of controller info
      effect = 0
      while (effect < nr of effects)
      {
        read 2 bytes
        effect id = the 4 top bits of the first byte
        effect value = second byte + 4 low bits of second byte * 256
      }
    }

    // channels
    while ( < row length)
    {
      read channel info (1 byte)
      channel nr = bottom 6 bits of channel info
      if (channel info and 0x40)
        read note (1 byte)
      if (channel info and 0x80)
        read instrument nr (1 byte)

      // channel effects (grouped by controller)
      repeat
      {
        read controller info (1 byte)
        if (controller info = 0)
          exit repeat

        nr of effects = the 4 high bits of controller info
        ctrl id = the 4 low bits of controller info
        effect = 0
        while (effect < nr of effects)
        {
          read 2 bytes
          effect id = the 4 top bits of the first byte
          effect value = second byte + 4 low bits of second byte * 256
        }
      }
    }
  }
}

Has you can see an empty row will be store as 2 bytes (= length of 0).
Channels will be stored by increasing channel number and only if there
is some info in that channel.





3) Controllers and Effects

3.a) Generic controller info and effects

The information is basically valid for tempo, volume, panning and pitch
controllers. Each controller defines:
- a range (min-max) of accepted values.
- a start value which is the value propagated from frame to frame.
- a delta value which is an offset applied from the duration of the current
  frame (i.e. reset to 0 each frame before effects are applied).
- a target value for portamento.
- a memory bank for portamento speed.
- a memory bank 1 slide speed and slide effect.
- a memory bank 2 slide speed and slide effect (not implemented)
  memory banks for vibrato position, speed, depth and type.
 
The commands that follow are always 2 bytes wide, where uppercase letters
stands for an hex code (4 bits) and lowercase letters for a single bit.


0xxxxXX  Set
         At frame 0, forces the start and target values to x.

1xxxxXX  Portamento Target
         At frame 0, sets the target value for Portamento effects, i.e.
         the value to slide to.

2zyxxXX  Up (without memory)
         Slides the start value up by x:
         - at frame 0 if bit z is set
         - at non-0 frames if bit y is set
         - at retrig count.

3zyxxXX  Down (without memory)
         Slides the start value down by x:
         - at frame 0 if bit z is set
         - at non-0 frames if bit y is set
         - at retrig count.

4zyxxXX  Up (with memory bank 1)
         Slides the start value up by x at frame 0 if bit z is set and/or
         at non-0 frames if bit y is set.
         If zy or x are not given they are loaded from memory bank 1.
         On exit zyx is stored in memory bank 1.

5zyxxXX  Down (with memory bank 1)
         Slides the start value down by x at frame 0 if bit z is set and/or
         at non-0 frames if bit y is set.
         If zy or x are not given they are loaded from memory bank 1.
         On exit zyx is stored in memory bank 1.

6zyxxXX  Up (with memory bank 2)
         As effect 1, but with a seperate memory bank.
         Note: required because of the volume column of Impulse Tracker.
         Note: implemented with memory bank 1.

7zyxxXX  Down (with memory bank 2)
         As effect 2, but with a seperate memory bank.
         Note: required because of the volume column of Impulse Tracker.
         Note: implemented with memory bank 1.

8zyxxXX  Portamento (with portamento memory bank)
         Slides the start value by x toward its target value (see effect
         Portamento Target) at frame 0 if bit z is set and/or at non-0
         frames if bit y is set.
         If zy or x are not given they are loaded from memory bank 1.
         On exit zyx is stored in memory bank.

9XXX     Set Vibrato Speed
         Set vibrato speed in memory bank to X if x is non-zero.
         See Vibrato effect just below.

AzyxxXX  Vibrato
         Vibrates the volume according to the low defined by in a table
         of 256 fractions in range [-1, 1]. 
         If vibrato depth (x) is not given it is loaded from memory bank
         else vibrato depth is stored in memory bank.
         At each frame the delta value is offset by
           Frac[MOD(pos, 256)] * x * vibrato strength
         Updates position x at frame 0 if bit z is set and/or
         at non-0 frames if bit y is set as follow:
           pos = pos + vibrato speed (memory).

         Should appear in an effect list after the "Set Vibrato Speed"
         command to ensure that it works properly.

E0izxxx  Vibrato Type
         At frame 0, sets the vibrato type parameters, x being the table
         to use, z the effect of new notes, i a sign inversion flag.
         Defined x tables:
           0 Sinus
           1 Square
           2 Ramp Up
           3 Ramp Down
           4 Random values
           5 Saw
           6 Half Square (i.e. [max, 0] not [max, -max])
         Effect z of new notes:
           0 Position within the table is reset when a new note is started
           1 The position within the table is left unmodified.
         Effect of flag i:
           0 Use table value
           1 Use table value but invert its sign.

E1zyoo0  Last slide
         Slide the start value using the slide direction and value (x)
         memorised in bank 1. If (zy) is 0, then it also uses
         the slide type (zy) memorised in bank 1.

E2XX     Vibrato Strength
         Sets the factor that multiplies the vibrato depth.
         The default strength depends on the controller (pitch, volume, ...)
         and on the tracker.





3.b) Global controllers

These controllers affects global variables.

3.b.1) Song Flow controller

A song is composed of a sequence of patterns, patterns of a sequence of rows
which in turn are played for the duration of a given amount of frames.
The position of a song is defined by its position in the sequence of
patterns, the current row in the corresponding pattern, the current frame
and the time spent within the current frame.

The normal behaviour once a row is played is to play the next row in the
current pattern, or if none remains, the first row of the next pattern
in the sequence. Effects applied here will alter this behaviour, and thus
take only effect after the row is played.

0XYY  Loop
      Used to set loops within the current pattern, y is the loop id (channel)
      and x the number of times to loop. The loop will start in row 0 (*) unless
      a Loop 0yy is encountred in a row while playing (so beware of Break
      commands) which marks that row as the start of the loop yy. When the
      player encounters a Loop xyy command with x <> 0 in a row it will play
      that row and jump to the start of the loop yy, till the loop is
      repeated x times.
      (*) Only on S3M, other trackers don't reset the loop position on pattern
      changes.
      Multiple loops in a given row are processed at the same time and
      the active loop with the highest id is taken. This means that the number
      of loops on that row is the lowest common multiple of all the loop
      counters, not the multiplication of all the loop counters.
      If a pattern contains for a given loop id a single start (with x = 0)
      followed my 2 or more loop ends, this leads to an infinite loop
      as the first loop end resets the loop counter for the second loop.
      Note in this case that the loop counter counts down from the number
      of repeats toward 0 (it affects the number of loops in the first loop
      after the second loop activates).
      Some trackers move the loop start after the loop end once the loop
      becomes inactive to try to avoid infinite loops.
      A flag to control this behaviour is defined in the song header.
      It should be noted though that an infinite loop can then still
      be triggered by combining the previous case with loops using other ids.

1XXX  Jump
      When the current row is played, move to the pattern specified
      by sequence position x. The move is to row 0 unless a Break or Line jump
      command is also present.

2XXX  Break
      When the current row is played, move to row x of next pattern unless
      a Jump command is also present in which case it jumps to row x of the
      pattern of the sequence position specified by the Jump command.

3XXX  Line jump
      When the current row is played, move to row x of current pattern unless
      a Jump command is also present in which case it jumps to row x of the
      pattern of the sequence position specified by the Jump command.

The new row and/or sequence position is taken after all effects are processed
so if multiple jumps, breaks or line jumps are present in a row, only
the latest change will be effective.




3.b.2) Song Tempo controller

The tempo controller manages either the tempo or the BPM depending on the mode
in use. By default if works in tempo mode.

The tempo ranges and tempo base depends on the tracker. For MOD the range
is [32-255] and the base is 2.5 so that a value of 125 gives 50 frames per
second.

BPM range is hardcoded to [1-256] at the moment.
Conversion of BPM to tempo is BPM * FPB * <tempo base> / 60.

0xxxxXX  Set
         At frame 0, forces the start and target values to x.
         Switches the controller to tempo mode.

1xxxxXX  Portamento Target
         At frame 0, sets the target value for Portamento effects, i.e.
         the value to slide to.

2zyxxXX  Up (without memory)
         Slides the start value up by x at frame 0 if bit z is set and/or
         at non-0 frames if bit y is set.

3zyxxXX  Down (without memory)
         Slides the start value down by x at frame 0 if bit z is set and/or
         at non-0 frames if bit y is set.

4zyxxXX  Up (with memory bank 1)
         Slides the start value up by x at frame 0 if bit z is set and/or
         at non-0 frames if bit y is set.
         If zy or x are not given they are loaded from memory bank 1.
         On exit zyx is stored in memory bank 1.

5zyxxXX  Down (with memory bank 1)
         Slides the start value down by x at frame 0 if bit z is set and/or
         at non-0 frames if bit y is set.
         If zy or x are not given they are loaded from memory bank 1.
         On exit zyx is stored in memory bank 1.

6zyxxXX  Up (with memory bank 2)
         As effect 1, but with a seperate memory bank.
         Note: required because of the volume column of Impulse Tracker.
         Note: implemented with memory bank 1.

7zyxxXX  Down (with memory bank 2)
         As effect 2, but with a seperate memory bank.
         Note: required because of the volume column of Impulse Tracker.
         Note: implemented with memory bank 1.

8zyxxXX  Portamento (with portamento memory bank)
         Slides the start value by x toward its target value (see effect
         Portamento Target) at frame 0 if bit z is set and/or at non-0
         frames if bit y is set.
         If zy or x are not given they are loaded from memory bank 1.
         On exit zyx is stored in memory bank.

AxxxxXX  Set BPM
         At frame 0, forces the start and target values to x.
         Switches the controller to BPM mode.

BxxxxXX  Set FPB
         At frame 0, sets the value of FPB (frames per beats).

CxxxxXX  Set large
         Identical to "Set" but value must be multiplied by 16.

DxxxxXX  Portamento Target large
         Identical to "Portamento Target" but value must be multiplied by 16.

E100     Last slide
         Slide the start value using the slide direction, type (zy) and
         value (x) memorised in bank 1.





3.b.3) Song Frames controller

Controls in number of frames the default duration of rows and the duration
of the current row. Such effects will be applied only when a new row starts,
never at each frame start. The controller affects 3 variables: speed, repeats
and delay. Repeats and delay are reset to 0 before calling the controller
which applies the effects. On exit, the number of frames a row is played
is calculated as: (speed + delay) * (1 + repeats). The default speed is
usually 6.

0XXX  Set Speed
      Sets the number of frames a row is played until the new row can start. 

1XXX  Up
      Increases the number of frames by x.

2XXX  Down
      Decreases the number of frames by x.

EXXX  Repeat
      This will force the row to be repeated x times.
      Note that for Impulse Tracker, non-deleayed notes will be applied
      only onthe first occurence of the row.

FXXX  Delay
      This will increase the current row duration by x frames.





3.b.4) Global Volume controller

Controls the overal volume of the song. Volume is in range [0x000 (mute) ..
0x100 (max and default)]. See generic controller for details of the effects.





3.c) Channel controllers

3.c.1) Channel Volume controller

Controls the overal volume of the channel. Volume is in range [0x000 (mute) ..
0x100 (max and default)]. See generic controller for details of the effects.





3.d) Notes: sample, pitch, filter, volume and panning

pitch = channel controller pitch
      + finetune
      + relative tone
      + pitch offset from instrument envelope (0 if none or not active)
      + instrument autovibrato

if (pitch > max note) and cut_high_pitch option -> cut note
else bound pitch between min and max notes.
if glissando snap pitch to the nearest semintone.


Filter is a resonant filter which transforms the output of a sample
(at the mixing frequency) as follows:
y0 = A0 * x0 + B1 * y1 + B2 * y2

x0 is input[t], yi is output[t - i], Ai and Bi coefficients calculated
on basis of two paramters: cutoff and resonance (see s.Notes for the details).

The filter is ignored if cutoff is set to its max value and resonance is
set to 0.
 

panning = channel panning
        + (panning offset from instrument envelope
            * abs(channel panning - 128)/128)

where offset is 0 if no active envelope and channel panning is reset to 128
in case it was surround and an envelope is active.

volume = note volume * channel volume * instrument envelope volume
       * fadeout volume * global volume
       / (256 * 256 * 256 * 65536 * 256 / 65536)

where:
- All volumes are in range [0, 256] except for fadeout [0, 65536].
- The resulting volume is in range [0, 65536].
- Instrument envelope volume is 256 if none is active.
- Fadeout volume is 65536 while fadeout is inactive.
- the note volume controller is reset to the instrument's defaut volume
  when a new note is played (or the instrument is reset). The controller
  only affects the current note in the channel, not past notes.
  The channel volume controller is independant from notes and so affects
  all notes: past, present and future.
- the panning controller is somewhat a mix of a note and channel controller:
  it is at the base a note controller since an instrument may force
  its value, but it will affect future notes of instruments which do
  not enforce the panning.



3.d.1) Instrument/Sample controller

Controls special features linked to samples or instruments.

0YXX  Set Offset
      Sets byte y of the position within the sample of the current note to x.
      Valid bytes are in range [0 .. 3]. Values are memorised and can be
      triggered with y = F (value is treated as a number of samples)
      or E (value is treated as a number of bytes, i.e bit-depth dependant).
      If the sample is in reverse play mode, sets the offset from the end
      of the sample.

1XXX  Set Finetune
      Sets note finetune to x. The range is [0x800 (-8 haltone) .. 0xFFF
      (-1/256 semitone) .. 0x001 (1/(256 semitone) .. 0x7FF (2047/256
      semitone)].

20yX  Note Retrig
      If x is 0, the last values used is loaded from memory.
      On exit x is stored in memory.
      If y is 1, the volume change below is not applied on frame 0 (see MDL).

      Each time the retrig counter reaches the retrig delay, a new note
      identical to the previous note is trigerred with note volume effect x:
        0 Volume(n) = Volume(n - 1) (memory)
        1 Volume(n) = Volume(n - 1) - 4
        2 Volume(n) = Volume(n - 1) - 8
        3 Volume(n) = Volume(n - 1) - 16
        4 Volume(n) = Volume(n - 1) - 32
        5 Volume(n) = Volume(n - 1) - 64
        6 Volume(n) = Volume(n - 1) * 2/3
        7 Volume(n) = Volume(n - 1) * 1/2
        8 Volume(n) = Volume(n - 1)
        9 Volume(n) = Volume(n - 1) + 4
        A Volume(n) = Volume(n - 1) + 8
        B Volume(n) = Volume(n - 1) + 16
        C Volume(n) = Volume(n - 1) + 32
        D Volume(n) = Volume(n - 1) + 64
        E Volume(n) = Volume(n - 1) * 3/2
        F Volume(n) = Volume(n - 1) * 2/1

      The retrig delay (a number of frames) is set with the 8YXX effect
      "Note Retrig Counter". The counter is updated by 1 (and reset after
      reaching the delay) on each frame of a row where the "Note Retrig Counter"
      effect is present.

      Should appear in an effect list after the "Note Retrig Counter" so that
      the retrig delay is correct when this effect is treated.

3YXX  Act on Current Note
      Apply one of the following actions y on the current note after a delay
      of x frames:
        0 Note Cut
        1 Note Off
        2 Note OffXM
        3 Note Fade
        4 Note Sustain Off

      If the delay exceeds the number of rows in frames, the action is never
      applied. A Note Cut (IT) or a Note OffXM (XM) reset the last note
      number, so retrigs become impossible.

4XXX  Note Delay
      Delay the triggering of the new note by x frames.
      If the delay exceeds the number of rows in frames, the action is never
      applied.

5YXX  Act on Past Notes
      Apply one of the following actions y on past notes after a delay
      of x frames:
        0 Note Cut
        1 Note Off
        2 Note OffXM
        3 Note Fade

      If the delay exceeds the number of rows in frames, the action is never
      applied.

6YXX  Set New Note Action
      Tells the current note to perform one of the following y action when
      a new note is triggered:
        0 Note Cut
        1 Note Off
        2 Note OffXM
        3 Note Fade
        5 Note Continue

70XX  Reverse Play
      Reverse playing direction, action is delayed by x frames.

71XX  Loop Off
      Forces sample loop off, action is delayed by x frames.

72XX  Loop Forward
      Forces sample loop to forward, action is delayed by x frames.
      Note that if loop start = loop end, there will be no loop.

73XX  Loop Bidirectional
      Forces sample loop to bidirectional, action is delayed by x frames.
      Note that if loop start = loop end, there will be no loop.

8YXX  Note Retrig Counter
      If x is 0, the last values used is loaded from memory.
      On exit x is stored in memory.

      X is the delay (in number of frames) between retrigs.
      Y is the type of retrig:

        0, MOD (E9v)
        Retrigs occurs at frames 0, delay + 1, 2* delay + 1, etc..

        1, IT (Quv)
        The command is not processed if no note is playing.

        When the effect is present on a row, the counter decreases
        till a <= 0 value is reached, at which point the new note is triggered.
        The counter is reset to x each time a note starts playing (normal
        or due to the retrig).
        As a consequence 0 values for x behave as a 1, changes of x
        due to a new retrig effect only take effect when the counter reaches 0
        and is reinitialised.
        Retrigs with x > speed will work provided that you put enough 81XX in
        the rows that follows (they can even be interspaced by other effects).

        2, XM (Ruv)
        When the effect is present on a row, the counter increases
        till a >= x value is reached, at which point the new note is triggered.
        The counter is reset to 0 each time a note starts playing (normal
        or due to the retrig).
        As a consequence, on a row that has a new note and x = 3 the new note
        is played at tick 0, and retrigs follows at tick 2, 5, 8, etc.
        Retrigs with x > speed will work provided that you put enough 82XX in
        the rows that follows (they can even be interspaced by other effects).

        3, XM Old (E9v)
        When the effect is present on a row, the counter is set to x on tick 0
        of the row, decremented at each tick and triggers a new note when
        the counter reaches 0. At that point the counter is reset to x.
        x = 0 will provoque a retrig at each tick of the row, x = 1 at ticks
        1, 3, 5, etc. If x > speed then there will be no retrig.

        4, S3M (Quv)
        The command is not processed if no note is playing.

        When the effect is present on a row, the counter increases till a >= x
        value is reached, at which point the new note is triggered and the
        counter is reset to 0. The counter is not reset by a new row or a new
        note, but every time the previous row doesn't countain a retrig effect.
        Also x = 0 does nothing.

        5, PTM (Huv)
        When the effect is present on a row, the counter is set to x on tick 0
        of the row but only if x > 0, decremented at each tick and triggers
        a new note when the counter reaches 0. At that point the counter
        is reset to x.
        Using frame 0 of the last row where the effect was used with x > 0,
        retrig occurs after delay-1, 2*delay-1, etc.

90YX  Gapper
      Turns the note on for y+1 frames and pauses for x+1 frames.
      It is similar to the Tremor XM effect but here the sample is paused
      instead of silenced.
      On and off times are memorised and if x = y = 0 the corresponding
      memorised values will be used.
      Uses the note_inst_flag_paused flag to signal that the note must be
      paused.

      Decreases counter by 1 each non-0 frame.
      If new value < 0:
      - switches on/off mode
      - resets counter to on/off value
      - turn off/on note_inst_flag_paused.
      On frame 0, force a switch to on mode and reset counter if a new note
      is played.
      External event: A new note does not touch counter and mode
      but resets note_inst_flag_paused.

      This means that:
      - new gapper settings take only effect after the next on/off switch.
      - even after stopping to use gapper effect, the note will remain
        paused if note_inst_flag_paused is still set.
      - a new note starts with a whole on time if a gapper effect is
        specified on the same line otherwise for the next gapper effect:
        - if gapper is in off mode the note will be audible for the remaining
          of the off time and the on time that follows.
        - if gapper is in on mode the note will be audible for the remaining
          of the on time.
AXXX  Upcall
      Mark upcall as set with value to x. Upcall is reset once read from API.
      Only of use by player modules emulators to trigger code callbacks.



3.d.2) Pitch/Filter controller

Controls the pitch of the current note in the channel. The player supports
3 different pitch definitions:
- Amiga periods, sometimes refered to as logarithmic mode.
  The controller values are in 1/256 of Amiga period (central note = 428*256,
  value is divided by 2 one octave higher, by 4 two octaves higher, ...).
  In terms of frequency the relation is:
    sample frequency * (period of cental note / x)
  Slide effects are in 1/4 of Amiga period (= IT extra fine slide).
- IT/XM "linear" mode.
  The controller values are in 1/256 semitones (central note = 64*256,
  value is x*256 higher x semitones higher).
  In terms of frequency it is actually an exponential mode:
    sample frequency * 2^((x - 64*256)/(12*256))
  Slide effects are in 1/64 semitones (= IT extra fine slide).
- Fraction mode (Coconizer).
  The controller values are in 1/65536 of base frequency (central note = 65536,
  value is multiplied by 2 one octave higher, by 4 two octaves higher, ...).
  In terms of frequency the relation is:
    sample frequency * x/65536
  Slide effects are in 16/65536 of base frequency.

Pitch range depends on the type of song loaded, with a coverage of 3 octaves
for MODs to 10 octaves for ITs.

See Generic controller for details of effects, thought there are no Set nor
Portamento Target commands which the player handles in another way, so they
are replaced by other commands.

Since all effects numbers in pitch controller are used up, a second controller
number has been reserved for extra pitch effects. These effects are translated
back to the normal controller with an extra 0x10000 added to them.

01XXX    Set offset
         Set a note permanent offset to the pitch.
         Kind like a finetune but in the normal pitch units,
         not in fractions of a semitone.

0DZYX    Arpeggio
         Commands which cycles the pitch through a sequence of values named:
           N            pitch
           H            pitch + y semitones
           L            pitch + x semitones
           mL           pitch - x semitones

         The sequence is defined by the value of z as follow:
           0            NHL   (the classic one)
           1            mLNH
           2            NHNmL
           3            LLN

         For example if the NHL sequence is used, the following is played:
           frame 0	    pitch
           frame 1	    pitch + x semitones
           frame 2	    pitch + y semitones
           frame 3	    pitch
           frame 4	    pitch + x semitones
           frame 5	    pitch + y semitones
           ...

0F0XX    Up memory bank 3 (for XM)
         At frame 0, slides the start value up by x.
         If x is not present it is loaded from memory bank 3.
         In exit x is stored in memory bank 3.

0F1XX    Down memory bank 4 (for XM)
         At frame 0, slides the start value down by x.
         If x is not present it is loaded from memory bank 4.
         In exit x is stored in memory bank 4.

0F2XX    Up memory bank 5 (for XM)
         At frame 0, slides the start value up by x.
         If x is not present it is loaded from memory bank 5.
         In exit x is stored in memory bank 5.

0F3XX    Down memory bank 6 (for XM)
         At frame 0, slides the start value down by x.
         If x is not present it is loaded from memory bank 6.
         In exit x is stored in memory bank 6.

0F4zyxxX Up no memory, unit is semitones
         Slides the start value up by x semitones at frame 0 if bit z is set
         and/or at non-0 frames if bit y is set.

0F5zyxxX Down no memory, unit is semitones
         Slides the start value down by x semitones at frame 0 if bit z is set
         and/or at non-0 frames if bit y is set.

0F6XX    Set pitch to note
         At frame 0, sets the pitch to the value of Note number xx.

Since all effects numbers in pitch controller are used up, a second controller
number has been reserved for extra pitch effects.

10zyxxX  Up automatic (with memory bank 1)
         Slides the start value up by x at frame 0 if bit z is set and/or
         at non-0 frames if bit y is set.
         If x is non-0, store zyx is stored in memory bank 1, and tells
         the controller to automatically repeat this sliding in the next frames
         till told otherwise.
         If x is 0, stop automatic sliding.

11zyxxX  Down automatic (with memory bank 1)
         Slides the start value down by x at frame 0 if bit z is set and/or
         at non-0 frames if bit y is set.
         If x is non-0, store zyx is stored in memory bank 1, and tells
         the controller to automatically repeat this sliding in the next frames
         till told otherwise.
         If x is 0, stop automatic sliding.

12zyxxX  Portamento automatic (with memory bank 1)
         Slides the start value by x toward its target value (see effect
         Portamento Target) at frame 0 if bit z is set and/or at non-0
         frames if bit y is set.
         If x is non-0, store zyx is stored in memory bank 1, and tells
         the controller to automatically repeat this sliding in the next frames
         till told otherwise or till reaching the target.
         If x is 0, stop automatic sliding.

13zyxxX  Vibrato automatic
         Like vibrato but permanent.
         If x is non-0, store zyx is stored in memory, and tells
         the controller to automatically repeat this vibrato in the next frames
         till told otherwise.
         If x is 0, stop automatic sliding.
         
18zyxxXX Update memory bank 1
         If zy or x are not given they are loaded from memory bank 1.
         On exit zyx is stored in memory bank 1.
         Note: required for linked EF/G effects in Impulse Tracker.

19zyxxXX Update portamento memory bank
         If zy or x are not given they are loaded from memory bank 1.
         On exit zyx is stored in memory bank.
         Note: required for linked EF/G effects in Impulse Tracker.

1F0XX    Envelope Control
         At frame 0, activates (x <> 0) or deactivates (x = 0) envelope.

1F1XX    Envelope Position
         At frame 0, set the position of the envelope to envelope point x.

1F2XX    Glissando
         At frame 0, activates (x <> 0) or deactivates (x = 0) glissando
         control, i.e. the fact that pitch must be rounded to the nearest
         semitone.

1F3XX    Set filter resonance
         At frame 0, sets the filter's resonance to x (max is 127).

1F4XX    Set filter cutoff
         At frame 0, sets the filter's cutoff to x (max is 127).

1F5XX    Filter Envelope Control
         At frame 0, activates (x <> 0) or deactivates (x = 0) envelope.

1F6XX    Filter Envelope Position
         At frame 0, set the position of the envelope to envelope point x.


3.d.3) Note Volume controller

Controls the volume of the currently active note in the channel. Volume is
in range [0x000 (mute) .. 0x100 (max and default)]. See generic controller
for details of the effects.

A new note or instrument change will always reset the start value
of the controller to the default specified by the instrument.
This means that this controller will NEVER affect future notes.

Since all effects numbers in pitch controller are used up, a second controller
number has been reserved for extra pitch effects. These effects are translated
back to the normal controller with an extra 0x10000 added to them.

BzyXX    Up exponential (with memory bank 1)
         Multiplies the start value by 2^(x/256) at frame 0 if bit z is set
         and/or at non-0 frames if bit y is set.
         If zy or x are not given they are loaded from memory bank 1.
         On exit zyx is stored in memory bank 1.

CzyXX    Down exponential (with memory bank 1)
         Divides the start value by 2^(x/256) at frame 0 if bit z is set
         and/or at non-0 frames if bit y is set.
         If zy or x are not given they are loaded from memory bank 1.
         On exit zyx is stored in memory bank 1.

DZYX     Tremor
         Repeatedly turns the note on for y frames and off for x frames.
         Z specifies the implementation to use.

D0YX     Tremor IT
         Turns the note on for y frames and off for x frames.
         On and off times are memorised and if x = y = 0 the corresponding
         memorised values will be used.
         The note volume is forced to zero while the effect is in use
         and in its off mode.

         Decreases counter by 1 each frame.
         If new value <= 0:
         - switches on/off mode
         - resets counter to memorised on/off value
         No external events (such as new notes) affect the counter.

         This means that:
         - changes in y/x values take only effect on the next on/off switch
         - values of 0 behave has value 1.

D1YX     Tremor IT Old effects.
         As Tremor IT but with on and off times of x+1 and y+1.

D2YX     Tremor XM
         Turns the note on for y+1 frames and off for x+1 frames.
         On and off times are memorised and if x = y = 0 the corresponding
         memorised values will be used.
         Uses the ch_flags_zero_volume flag to signal that the note must be
         silenced.

         Decreases counter by 1 each non-0 frame.
         If new value < 0:
         - switches on/off mode
         - resets counter to on/off value
         - turn off/on ch_flags_zero_volume.
         On frame 0, force a switch to on mode and reset counter if a new note
         is played.
         External event: A new note does not touch counter and mode
         but resets ch_flags_zero_volume.

         This means that:
         - new tremor settings take only effect after the next on/off switch.
         - even after stopping to use tremor effect, the note will remain
           silent as ch_flags_zero_volume is still set.
         - a new note starts with a whole on time if a tremor effect is
           specified on the same line otherwise for the next tremor effect:
           - if tremor is in off mode the note will be audible for the remaining
           of the off time and the on time that follows.
           - if tremor is in on mode the note will be audible for the remaining
           of the on time.

D3YX     Tremor S3M
         Turns the note on for y+1 frames and off for x+1 frames.
         On and off times are memorised and if x = y = 0 the corresponding
         memorised values will be used.
         Uses the ch_flags_zero_volume flag to signal that the note must be
         silenced.

         Decreases counter by 1 each frame.
         If new value < 0:
         - switches on/off mode
         - resets counter to on/off value
         - turn off/on ch_flags_zero_volume.
         External event: A new note does not touch counter and mode
         but resets ch_flags_zero_volume.

         This means that:
         - new tremor settings take only effect after the next on/off switch.
         - even after stopping to use tremor effect, the note will remain
           silent as ch_flags_zero_volume is still set.
         - after a new note, for the tremor that follows:
           - if tremor is in off mode the note will be audible for the remaining
           of the off time and the on time that follows.
           - if tremor is in on mode the note will be audible for the remaining
           of the on time.

D4YX     Tremor MDL
         Turns the note on for y frames and off for x frames.
         On and off times are memorised and if x = y = 0 the corresponding
         memorised value will be used, otherwise that value is memorised.

         Resets the counter at each 0-frame.
         If off time = 0, remain always on, else:
         Decreases counter by 1 each non-0 frame.
         If new value <= 0:
         - switches on/off mode
         - resets counter to on/off value

         This means that:
         - each row starts in on mode for a whole on time.
         - an on time of 0 behaves as an on time of 1.

F0XX     Envelope Control
         At frame 0, activates (x <> 0) or deactivates (x = 0) envelope.

F1XX     Envelope Position
         At frame 0, set the position of the envelope to envelope point x.

F2XX     Cut volume
         Set volume to 0 after XX frames.
         

100zyxxX Up automatic (with memory bank 1)
         Slides the start value up by x at frame 0 if bit z is set and/or
         at non-0 frames if bit y is set.
         If x is non-0, store zyx is stored in memory bank 1, and tells
         the controller to automatically repeat this sliding in the next frames
         till told otherwise.
         If x is 0, stop automatic sliding.

110zyxxX Down automatic (with memory bank 1)
         Slides the start value down by x at frame 0 if bit z is set and/or
         at non-0 frames if bit y is set.
         If x is non-0, store zyx is stored in memory bank 1, and tells
         the controller to automatically repeat this sliding in the next frames
         till told otherwise.
         If x is 0, stop automatic sliding.

120zyxxX Portamento automatic (with memory bank 1)
         Slides the start value by x toward its target value (see effect
         Portamento Target) at frame 0 if bit z is set and/or at non-0
         frames if bit y is set.
         If x is non-0, store zyx is stored in memory bank 1, and tells
         the controller to automatically repeat this sliding in the next frames
         till told otherwise or till reaching the target.
         If x is 0, stop automatic sliding.

130zyxxX Update memory bank 1
         If zy or x are not given they are loaded from memory bank 1.
         On exit zyx is stored in memory bank 1.




3.d.4) Panning controller

Controls the panning of a channel. Panning is in range [0x000 (Left) ..
0x080 (Front) .. 0x100 (Right)] and a special value of 0x180
(Behind/Surround). See generic controller for the details of the basic
effects.

A new note or instrument change may (or not) reset the start value
of the controller to the default specified by the instrument.

F0XX     Envelope Control
         At frame 0, activates (x <> 0) or deactivates (x = 0) envelope.

F1XX     Envelope Position
         At frame 0, set the position of the envelope to envelope point x.




4) Logging

During song loading some logging information is generated to signal corrupted
files, presence of unsupported effects, etc. This ouput was generated
under the TimPlayer SysLog by the module (disabled since 1.23 for performance
reasons) and under the standard error stream by the file to WAVE conversion
tool. The amount of output is controlled by with the SysLog level for the module
and by the verbose parameter (-v) in the conversion tool.

The levels are:
    001  Loading errors:
         - out of memory
         - song format not supported
         - invalid nr of channels, patterns, samples, instruments, orders
           an other badly corrupted files
    080  High level problems
         - missing, incorrectly decompressed or seriously truncated samples
         - incorrect pattern encoding
    160  Medium level problems
         - minor sample truncation
         - truncated patterns
         - unsupported dat blocks
    240  Low level corruption 
         - extra channels in pattern encoding
         - contradictory informations
    251  Invalid Note
    252  Unimplemented effect
    253  Unimplemented effect value
    254  Unkown effect
    255  Incorrect effect value     




5) Limitations

Samples     [1-255] (1 byte of storage in patterns, inst maps, ...)
Instruments [1-255] (1 byte of storage in patterns, ...)
Patterns    256     IIRC, no reason.
P. rows     512     No reason, only a few DMFs slightly exceed 256 rows.
Channels    64      (6-bits of storage in patterns)
Polyphony   64      (max 256? but limited cf. SA RPC CPU and mix buffers)
Speed       255     Cf saved as one byte in SecTempos



6) Volume ramping

With this option active, the player will segment the start of the frame
to progressively ramp the settings (volume, panning, frequency) of a playing
note from those in the previous frame to the new ones. For new notes starting
to play in the new frame it is just the volume that will be ramped from 0
to the actual value.

Also at the end of the frame if will in the same manner ramp the volume
of notes that will be cut in the next frame to 0.

For the last operation, it means that we must must already partially
process the next frame: like maybe point to anew row/pattern with other effects
and determine if those effects will cut a note. but we still continue to
play the current frame. This means that all the processing done for a new
frame is split in 2 parts: a pre-processing before starting the ramp
and the actual processing once the ramp is completed.

Note:
Volume ramping is disabled for high tempo when frame duration is inferior
to 3 times the duration of the ramp at start/end of a frame. Going below
2 times will cause the player to start the row pre-processing but never
reaching the processing part.
